package cn.d2005.attachdemo.control;

import cn.d2005.attachdemo.model.Order;
import cn.d2005.attachdemo.service.OrderService;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/order")

public class OrderServlet {
    @Resource
    private FastFileStorageClient client;
    @Resource
    private OrderService orderService;

    @RequestMapping("/list")
    public String list(Model model){
        List<Order> orderList=orderService.findList();
        model.addAttribute("orderList",orderList);
        return "list";
    }

    @PostMapping("/saveAdd")
    public String add(Order order,MultipartFile attach, HttpServletRequest req){//MultipartFile获取附件对象
        String fileName=null;
        if(attach!=null&&!attach.isEmpty()){
            //获取文件名
            fileName=attach.getOriginalFilename();
            //获取存储路径
//            String path=req.getServletContext().getRealPath("/static/upload");
            StorePath storePath=null;
//            File file=new File(path+File.separator+fileName);

//                attach.transferTo(file);//转存文件
            try {
                //转存文件到fastDFS
                storePath=client.uploadFile(null,
                        attach.getInputStream(),
                        attach.getSize(),
                        fileName.substring(fileName.lastIndexOf(".")+1));
            } catch (IOException e) {
                e.printStackTrace();
            }

            order.setAttachFileName(fileName);
            order.setAttachFilePath(storePath.getPath());
            order.setAttachFilePathGroup(storePath.getGroup());
        }

        order.setCreateTime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        orderService.addOrder(order);
        return "redirect:list";
    }

    @GetMapping("/download")
    public void download(Integer id, HttpServletResponse resp){

        Order order=orderService.selectById(id);
        String fileName=order.getAttachFileName();
        try {

            //new String(byte[],decode)实际是使用指定的编码decode来将byte[]解析成字符串
            //原因 下载界面编码集是ISO8859-1(解决中文名文件下载乱码问题)
            fileName=new String(fileName.getBytes("UTF-8"),"ISO8859-1");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //设置反馈内容下载窗口模式attachment 此处的fname为文件下载后的名字
        resp.setHeader("Content-Disposition", "attachment;filename="+fileName);

        //下载：
        //声明一个接受字节数组
        DownloadByteArray buff=new DownloadByteArray();

        //利用FastFileStorageClient 工具类下载

        String downloadPath=order.getAttachFilePath();

        //infos即下载好的文件字节
        byte[] infos=client.downloadFile("group1",downloadPath,buff);

       OutputStream ot=null;
        try {
            ot=resp.getOutputStream();
            ot.write(infos,0,infos.length);
            ot.flush();
            ot.close();
            System.out.println("正在下载"+fileName);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return ;
    }


}
